package br.ufc.great.dtxtester.operation;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Random;
import java.util.Vector;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

/**
 * 
 * @author Leonardo Oliveira Moreira
 *
 * Classe utilizada para recuperar opera��es de consulta atrav�s de um arquivo XML com exemplos de consultas
 */
public class QueryOperations {

	private Document document;
	private Random random;
	private Vector<QueryOperation> queryOperations;

	/**
	 * Construtor
	 * 
	 * @param fileName
	 * @throws IOException
	 */
	public QueryOperations(String fileName) throws IOException {
		SAXBuilder saxBuilder = new SAXBuilder();
		String appPath = System.getProperty("user.dir");
		if (appPath.endsWith("bin"))
			appPath = appPath.substring(0, appPath.length() - "bin".length());
		appPath += System.getProperty("file.separator");
		File file = new File(appPath + fileName);
	    try {
			document = saxBuilder.build(file);
			random = new Random();
		    Element queryOperationsRoot = document.getRootElement();
		    List queryOperationsList = queryOperationsRoot.getChildren();
		    queryOperations = new Vector<QueryOperation>();
		    for (int i = 0; i < queryOperationsList.size(); i++) {
		    	Element item = (Element) queryOperationsList.get(i);
		    	String id = item.getAttributeValue("id");
		    	String query = item.getValue().trim();
				QueryOperation operation = new QueryOperation();
				operation.setId(id);
				operation.setQuery(query);
				queryOperations.add(operation);
		    }
		}
	    catch (JDOMException e) {
			throw new IOException(e.getMessage());
		}
	    catch (IOException e) {
			throw e;
		}
	}
	
	/**
	 * Método que retorna aleatoriamente uma opera��o de consulta contida no arquivo
	 * 
	 * @return
	 */
	public QueryOperation getOperation() {
	    if (queryOperations != null && queryOperations.size() > 0) {
	    	return queryOperations.elementAt(random.nextInt(queryOperations.size() - 1));
	    }
		return null;
	}
	
	public QueryOperation getOperation(String id) {
		for (int i = 0; queryOperations != null && i < queryOperations.size(); i++) {
			QueryOperation queryOperation = queryOperations.elementAt(i);
			if (queryOperation.getId().equalsIgnoreCase(id))
				return queryOperation;
		}
		return null;
	}
	
}
